//
//  UIImage+JKExtension.m
//  01-百思不得姐
//
//  Created by albert on 16/3/28.
//  Copyright (c) 2016年 albert. All rights reserved.
//

#import "UIImage+JKExtension.h"

@implementation UIImage (JKExtension)
- (UIImage *)circleImage{
    
    CGFloat width = self.size.width;
    CGFloat height = self.size.height;
    if (width != height) {
        width = MIN(width, height);
    }
    
    width = width > 100 ? 100 : width;
    height = width;
    
    //NO代表透明
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), NO, 0.0);
    
    //获取上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    //添加一个圆
    CGRect rect = CGRectMake(0, 0, width, height);
    CGContextAddEllipseInRect(ctx, rect);
    
    //裁剪
    CGContextClip(ctx);
    
    //将图片画上去
    [self drawInRect:rect];
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
}

/** 返回带有圆形边框的圆形图片 */
- (UIImage *)circleImageWithBorderColor:(UIColor *)borderColor borderWidth:(CGFloat)borderWidth{
    //需求：从位图上下文，裁剪图片[剪成圆形，也添加圆形的边框，生成一张图片]
    
    CGFloat width = self.size.width;
    CGFloat height = self.size.height;
    if (width != height) {
        width = MIN(width, height);
    }
    width = width > 100 ? 100 : width;
    height = width;
    
    //获取要裁剪图片
    CGRect imageRect = CGRectMake(0, 0, width, height);
    
    //1、开启位图上下文
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), NO, 0.0);
    
    // 在自定义的view的drawRect方法里，调用UIGraphicsGetCurrentContext()获取的上下文，是图层上下文（Layer Graphics Context）
    //1.1获取位图上下文
    CGContextRef bitmapContext = UIGraphicsGetCurrentContext();  //此处是获取的位图上下文
    
    //2、往位图上下文裁剪图片
    //2.1指定一个圆形的路径，把圆形之外的剪切掉
    CGContextAddEllipseInRect(bitmapContext, imageRect);
    CGContextClip(bitmapContext);
    
    //2.2添加图片
    [self drawInRect:imageRect];
    
    //2.3添加边框
    [borderColor set];
    CGContextSetLineWidth(bitmapContext, borderWidth);
    CGContextAddEllipseInRect(bitmapContext, imageRect);
    CGContextStrokePath(bitmapContext);  //记得渲染
    
    //3、获取当前位图上下文的图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    //4、结束位图编辑
    UIGraphicsEndImageContext();
    
    return newImage;
}
@end
